package com.jf3q.front.intercept;

import com.alibaba.fastjson.JSON;
import com.jf3q.common.utils.JwtTokenUtil;
import com.jf3q.common.vo.ResultVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;

@Component
public class TokenInterception implements HandlerInterceptor {

    @Autowired
    JwtTokenUtil jwtTokenUtil;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

         String requestURI = request.getRequestURI().toLowerCase();  // 将请求URI转换为小写

        // 判断请求是否为图片或视频资源，如果是，则直接放行
        if (requestURI.endsWith(".png") || requestURI.endsWith(".jpg") || requestURI.endsWith(".jpeg")
                || requestURI.endsWith(".gif") || requestURI.endsWith(".mp4") || requestURI.endsWith(".avi")) {
            return true;
        }

        //看下token在不在
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResultVo.error(30001,"token不存在")));
            writer.flush();
            writer.close();
            return false;
        }

        //校验token是否合法
        if (!jwtTokenUtil.validateToken(token)) {
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResultVo.error(30002,"token有问题")));
            writer.flush();
            writer.close();
            return false;
        }


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
